package com.beiding.listener;

import com.beiding.dao.OrderDao;
import com.beiding.dao.SettingsDao;
import com.beiding.pojo.order.Order;
import com.beiding.service.RoomStorageService;
import com.beiding.service.impl.MessageSender;
import com.beiding.timeout.bean.TimeShaft;
import com.beiding.utils.LogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Expire extends TimeoutListener {

    private RoomStorageService roomStorageService;

    private SettingsDao settings;

    @Autowired
    public void setSettings(SettingsDao settings) {
        this.settings = settings;
    }


    @Autowired
    public void setRoomStorageService(RoomStorageService roomStorageService) {
        this.roomStorageService = roomStorageService;
    }


    private MessageSender sender;

    @Autowired
    public void setSender(MessageSender sender) {
        this.sender = sender;
    }

    protected Expire(OrderDao orderDao, TimeShaft<String> timeShaft) {
        super(orderDao, timeShaft, "expire");
    }

    @Override
    public void run(String id) {
        Order order = orderDao.getInsensitive(id);

        if (judge(order, Order.USING)) {

            LogUtils.info(this.getClass(), "房间到期,订单正常结束.与房东分红");

            Float deposit = order.getDeposit();
            if (deposit == null) {
                orderDao.updateField(id, "state", Order.EVALUATE);
                roomStorageService.release(order.getRoomId());
                LogUtils.info(this.getClass(), "已释放对房源的占用");


                timeShaft.delay("evaluate", settings.getTimeout("evaluate"), order.getId());

                order.setState(Order.EVALUATE);

                sender.sendToTenant(order.getHolderId(),update(order));
                sender.sendToLandlord(order.getLandlord(),update(order));

            } else {

                orderDao.updateField(id, "state", Order.REFUND_DEPOSIT);
                roomStorageService.release(order.getRoomId());
                LogUtils.info(this.getClass(), "已释放对房源的占用");
                timeShaft.delay("refundDeposit", settings.getTimeout("refundDeposit"), id);

                order.setState(Order.REFUND_DEPOSIT);

                sender.sendToTenant(order.getHolderId(),update(order).msg("你有一笔订单到期,提醒房东退还押金"));
                sender.sendToLandlord(order.getLandlord(),update(order));
            }
        }
    }
}

